//
//  ViewController.swift
//  CountDown
//
//  Created by panda on 17/3/7.
//  Copyright © 2017年 panda. All rights reserved.
//

import UIKit
import Foundation
import UserNotifications

class ViewController: UIViewController {
    
    //定义一个标签UILabel来显示剩余时间；
    //定义了一排橘黄色的按钮UIButton，接受用户点击操作；
    //定义了启动/停止按钮和复位按钮，接受用户点击操作。

    var remainingSeconds : Int = 0 {
        willSet(newSecond){
            let min = newSecond / 60;
            let sec = newSecond % 60;
            timeLbl.text = NSString(format: "%02d:%02d", min, sec) as String;
        }
    }
    
    var isCount : Bool = false {
        willSet(value) {
            if value {
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true);
            }else {
                timer?.invalidate()
                timer = nil
            }
            setSettingButtonsEnabled(enable: !value)
        }
    }
    
    var timer : Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        setuptimeButtons();
        self.view.addSubview(timeLbl);
        self.view.addSubview(startStopButton);
        self.view.addSubview(clearButton);
        
        createAndFireLocalNotificationAfterSeconds()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews();
        timeLbl.frame = CGRect(x: 10, y:64 + 20, width: self.view.bounds.size.width - 20, height: 120);
        
        let width : CGFloat = 44;
        let gap = (self.view.bounds.size.width - (CGFloat(timeButtons.count) * width)) / CGFloat(timeButtons.count + 1);
        for (index, btn) in timeButtons.enumerated() {
            let btnX = (gap + width) * CGFloat(index) + gap;
            btn.frame = CGRect(x: btnX, y: timeLbl.frame.maxY + 30, width: width, height: width);
        }
        
        startStopButton.frame = CGRect(x: 10, y: self.view.bounds.size.height-60, width: self.view.bounds.size.width-20-100, height: 44)
        clearButton.frame = CGRect(x: 10+self.view.bounds.size.width-20-100+20, y: self.view.bounds.size.height-60, width: 80, height: 44)

    }
    
    //MARK: - 点击事件
    func timeButtonTapped(sender: UIButton) {
        let (_, second) = timeButtonInfos[sender.tag];
        remainingSeconds += second;
    }
    
    func startStopButtonTapped(sender: UIButton) {
        isCount = !isCount;
    }
    
    func clearButtonTapped(sender: UIButton) {
        remainingSeconds = 0;
        timer?.invalidate()
    }
    
    //MARK: - 其他方法
    func setuptimeButtons() {
        var buttens = [UIButton]();
        for (index, (title, _)) in timeButtonInfos.enumerated() {
            let btn : UIButton = UIButton();
            btn.tag = index;
            btn.setTitle("\(title)", for: UIControlState.normal);
            btn.backgroundColor = UIColor.orange;
            btn.setTitleColor(UIColor.white, for: UIControlState.normal);
            btn.setTitleColor(UIColor.black, for: UIControlState.highlighted);
            btn.addTarget(self, action: #selector(timeButtonTapped(sender:)), for: UIControlEvents.touchUpInside);
            buttens.append(btn);
            self.view.addSubview(btn);
        }
        timeButtons = buttens;
    }
    
    func updateTimer() {
        remainingSeconds -= 1;
        if remainingSeconds==0 {
            timer?.invalidate()
            timer = nil;
            isCount = false
            sendNotification()
        }
        
    }
    
    func setSettingButtonsEnabled(enable: Bool) {
        for (_, btn) in timeButtons.enumerated() {
            btn.isEnabled = enable;
            btn.alpha = enable ? 1.0 : 0.3
        }
        clearButton.isEnabled = enable;
        clearButton.alpha = enable ? 1.0 : 0.3
    }
    
    func createAndFireLocalNotificationAfterSeconds() {

        UNUserNotificationCenter.current().requestAuthorization(options: UNAuthorizationOptions.alert) { (granted, error) in
            print(granted);
            print(error ?? "no error");
            
            if granted {
                // 用户允许进行通知
//                let alert = UIAlertController.init(title: "提示", message: "是否同意打开推送", preferredStyle: UIAlertControllerStyle.alert);
//                let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
//                    
//                })
//                let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (UIAlertAction) in
//                    
//                })
//                alert.addAction(okAction)
//                alert.addAction(cancelAction);
//                self.present(alert, animated: true, completion: nil)
            }
        }
    }
    
    func sendNotification() {
        let content = UNMutableNotificationContent();
        content.title = "时间到啦";
        content.body = "喝水喝水";
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false);
        
        let requestIdentifier = "com.onevcat.usernotification.myFirstNotification";
        
        let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger);
        
        UNUserNotificationCenter.current().add(request) { (error) in
            if error == nil {
                print(("Time Interval Notification scheduled: \(requestIdentifier)"))
            }
        }
    }
    
    //MARK: - 懒加载
    fileprivate lazy var timeLbl : UILabel = {
        let lbl = UILabel();
        lbl.text = "00:00";
        lbl.textColor = UIColor.white;
        lbl.font = UIFont.systemFont(ofSize: 80);
        lbl.backgroundColor = UIColor.black;
        lbl.textAlignment = NSTextAlignment.center;
        return lbl;
    }()
    
    fileprivate lazy var startStopButton: UIButton = {
        let btn = UIButton(type: UIButtonType.custom);
        btn.setTitle("启动/停止", for: UIControlState.normal);
        btn.backgroundColor = UIColor.red;
        btn.setTitleColor(UIColor.white, for: UIControlState.normal);
        btn.setTitleColor(UIColor.black, for: UIControlState.highlighted);
        btn.addTarget(self, action: #selector(startStopButtonTapped(sender:)), for: UIControlEvents.touchUpInside);
        return btn;
    }()
    
    fileprivate lazy var clearButton: UIButton = {
        let btn = UIButton(type: UIButtonType.custom);
        btn.setTitle("复位", for: UIControlState.normal);
        btn.backgroundColor = UIColor.red;
        btn.setTitleColor(UIColor.white, for: UIControlState.normal);
        btn.setTitleColor(UIColor.black, for: UIControlState.highlighted);
        btn.addTarget(self, action: #selector(clearButtonTapped(sender:)), for: UIControlEvents.touchUpInside);
        return btn;
    }()
    //
    let timeButtonInfos = [("1分", 60), ("3分", 180), ("5分", 300), ("秒", 1)];
    var timeButtons = [UIButton]();
    

}

